<template>
  <div class="interview-management">
    <div class="section-header">
      <h2>面试预约管理</h2>
      <el-button type="primary" @click="refreshInterviews">刷新</el-button>
    </div>
    
    <div v-loading="loading">
      <!-- 我的面试预约 -->
      <el-card header="我的预约" class="interview-section">
        <div v-if="!appointmentList.length" class="empty-state">
          <el-empty description="暂无面试预约" />
        </div>
        <div v-else>
          <div v-for="apt in appointmentList" :key="apt.appointmentId" class="appointment-card">
            <div class="apt-header">
              <div class="apt-info">
                <h4>{{ apt.clubName }}</h4>
                <p>{{ apt.recruitmentTitle }}</p>
              </div>
              <el-tag :type="getAppointmentStatusStyle(apt.status)" size="large">
                {{ getAppointmentStatusText(apt.status) }}
              </el-tag>
            </div>
            
            <div class="apt-content">
              <p><el-icon><Calendar /></el-icon> {{ formatDate(apt.interviewDate) }}</p>
              <p><el-icon><Clock /></el-icon> {{ apt.startTime }} - {{ apt.endTime }}</p>
              <p><el-icon><Location /></el-icon> {{ apt.location }}</p>
              <p><el-icon><Phone /></el-icon> {{ apt.phone }}</p>
              <p v-if="apt.remarks"><strong>备注：</strong>{{ apt.remarks }}</p>
              <div v-if="apt.status === '2' && apt.feedback">
                <p><strong>面试反馈：</strong>{{ apt.feedback }}</p>
                <p><strong>面试评分：</strong>
                  <el-rate v-model="apt.score" disabled show-score />
                </p>
              </div>
            </div>
            
            <div class="apt-actions">
              <el-button 
                v-if="apt.status === '0' || apt.status === '1'" 
                type="danger" 
                size="small"
                @click="handleCancelAppointment(apt.appointmentId)"
              >
                取消预约
              </el-button>
            </div>
          </div>
        </div>
      </el-card>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, watch } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Calendar, Clock, Location, User, Phone } from '@element-plus/icons-vue'
import interviewManagementApi from '@/api/campus/student/interviewManagement'
import useUserStore from '@/store/modules/user'

// 使用解构赋值从默认导出中获取函数
const { 
  getStudentAppointments,
  bookInterview: apiBookInterview,
  cancelAppointment: apiCancelAppointment
} = interviewManagementApi

// Props
const props = defineProps({
  currentUserId: {
    type: String,
    required: false,
    default: ''
  }
})

// Data
const loading = ref(false)
const appointmentList = ref([])

// Methods
// 从多个可能的位置获取用户ID的辅助函数
  const getUserIdFromStorage = () => {
    // 打印所有localStorage键值对，调试用
    console.log('===== localStorage 内容分析 =====');
    for (let i = 0; i < localStorage.length; i++) {
      const key = localStorage.key(i);
      try {
        const value = localStorage.getItem(key);
        console.log(`localStorage[${key}]:`, value);
        
        // 特别检查用户相关的关键字段
        if (key.toLowerCase().includes('user') || 
            key.toLowerCase().includes('token') || 
            key.toLowerCase().includes('auth')) {
          console.log(`🚨 可能包含用户信息的字段: ${key}`);
          // 尝试解析为对象
          try {
            const parsed = JSON.parse(value);
            console.log(`解析后内容:`, parsed);
          } catch (e) {
            console.log(`不是JSON格式`);
          }
        }
      } catch (e) {
        console.log(`读取 ${key} 时出错:`, e);
      }
    }
    console.log('==================================');

    // 尝试从所有可能的位置获取用户ID
    let userId = '';
    
    // 1. 尝试从常见的用户ID字段获取
    const userIdKeys = ['userId', 'id', 'user_id', 'username', 'loginName', 'account'];
    for (const key of userIdKeys) {
      const value = localStorage.getItem(key);
      if (value && value.trim()) {
        userId = value;
        console.log(`1. 从 ${key} 获取到用户ID:`, userId);
        break;
      }
    }
    
    // 2. 尝试从userInfo对象中获取各种可能的用户ID字段
    if (!userId) {
      try {
        const userInfoStr = localStorage.getItem('userInfo') || localStorage.getItem('userinfo');
        if (userInfoStr) {
          const userInfo = JSON.parse(userInfoStr);
          console.log('发现userInfo对象:', userInfo);
          
          // 尝试所有可能的用户ID字段名
          const possibleIdFields = ['id', 'userId', 'user_id', 'username', 'loginName', 'account', 'studentId'];
          for (const field of possibleIdFields) {
            if (userInfo[field] && String(userInfo[field]).trim()) {
              userId = String(userInfo[field]);
              console.log(`2. 从userInfo.${field}获取到用户ID:`, userId);
              break;
            }
          }
        }
      } catch (e) {
        console.warn('解析userInfo失败:', e);
      }
    }
    
    // 3. 尝试从token或其他认证信息中获取
    if (!userId) {
      try {
        const tokenKeys = ['token', 'Authorization', 'auth_token', 'access_token'];
        let token = '';
        
        for (const key of tokenKeys) {
          token = localStorage.getItem(key);
          if (token) break;
        }
        
        if (token) {
          console.log('发现token:', token);
          // 简单尝试解码token前半部分
          try {
            const tokenParts = token.split('.');
            if (tokenParts.length >= 2) {
              const decoded = JSON.parse(atob(tokenParts[1].replace(/-/g, '+').replace(/_/g, '/')));
              console.log('token解码内容:', decoded);
              
              // 尝试所有可能的用户ID字段名
              const possibleIdFields = ['id', 'userId', 'user_id', 'username', 'loginName', 'account', 'sub', 'name'];
              for (const field of possibleIdFields) {
                if (decoded[field] && String(decoded[field]).trim()) {
                  userId = String(decoded[field]);
                  console.log(`3. 从token.${field}获取到用户ID:`, userId);
                  break;
                }
              }
            }
          } catch (e) {
            console.warn('解码token失败:', e);
          }
        }
      } catch (e) {
        console.warn('从token获取用户ID失败:', e);
      }
    }
    
    return userId;
  };

  // 获取有效的用户ID（优先使用store，其次是props，最后是localStorage）
  const getValidUserId = computed(() => {
    // 1. 从store获取用户ID（最高优先级）
    try {
      const userStore = useUserStore();
      if (userStore && userStore.id) {
        console.log('从store获取到用户ID:', userStore.id);
        return String(userStore.id).trim();
      }
    } catch (error) {
      console.warn('获取store用户信息失败:', error);
    }
    
    // 2. 从props获取userId
    const userIdFromProps = String(props.currentUserId || '').trim();
    console.log('props中的用户ID:', userIdFromProps);
    
    // 3. 检查localStorage中的userId
    const userIdFromStorage = getUserIdFromStorage();
    
    // 使用第一个有效的用户ID
    const validUserId = userIdFromProps || userIdFromStorage;
    
    console.log('最终有效用户ID:', validUserId);
    return validUserId;
  });

  const loadInterviews = async () => {
    const validUserId = getValidUserId.value;
    console.log('开始加载面试信息，用户ID:', validUserId);
    
    if (!validUserId || validUserId === 'undefined' || validUserId === 'null' || validUserId.trim() === '') {
      console.warn('用户ID为空，无法加载面试信息');
      ElMessage.warning('请先登录后再查看面试信息');
      return;
    }
    
    try {
      loading.value = true;
      // 获取我的面试预约 (使用学生专用接口)
      const appointmentsResponse = await getStudentAppointments(validUserId);
      if (appointmentsResponse.code === 200) {
        appointmentList.value = (appointmentsResponse.data || []).map(apt => ({
          ...apt,
          clubName: apt.clubName || '未知社团',
          recruitmentTitle: apt.recruitmentTitle || '未知职位'
        }));
      } else {
        console.warn('获取面试预约失败:', appointmentsResponse.msg);
        ElMessage.error(appointmentsResponse.msg || '获取面试信息失败');
        appointmentList.value = [];
      }
    } catch (error) {
      console.error('加载面试信息失败:', error);
      ElMessage.error('获取面试信息异常');
      appointmentList.value = [];
    } finally {
      loading.value = false;
    }
  };

const refreshInterviews = () => {
  loadInterviews();
  ElMessage.success('面试信息已刷新');
}

const handleCancelAppointment = async (appointmentId) => {
  try {
    await ElMessageBox.confirm('确定要取消这个面试预约吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    });
    
    const response = await apiCancelAppointment(appointmentId);
    if (response.code === 200) {
      ElMessage.success('预约已取消');
      loadInterviews();
    } else {
      ElMessage.error(response.msg || '取消失败');
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('取消预约失败:', error);
      ElMessage.error('网络错误，请稍后重试');
    }
  }
}

// 监听用户ID变化
watch(() => props.currentUserId, (newUserId) => {
  // 即使props没有变化，也尝试从localStorage获取用户ID
  loadInterviews();
})

// Utility functions
const getAppointmentStatusText = (status) => {
  const map = { '0': '待面试', '1': '已预约', '2': '已完成', '3': '已取消' };
  return map[status] || '未知状态';
}

const getAppointmentStatusStyle = (status) => {
  const map = { '0': 'warning', '1': 'primary', '2': 'success', '3': 'info' };
  return map[status] || 'default';
}

const formatDate = (date) => {
  return date ? new Date(date).toLocaleDateString('zh-CN') : '未知日期';
}

// Initialize
onMounted(() => {
  // 无论props中是否有用户ID，都尝试加载数据（会从localStorage获取）
  loadInterviews();
})

// Expose methods for parent component
defineExpose({
  loadInterviews,
  refreshInterviews
})
</script>

<style scoped>
.interview-management {
  max-width: 1200px;
  margin: 0 auto;
  padding: 30px 20px;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
}

.section-header h2 {
  margin: 0;
  color: #303133;
}

.interview-section {
  margin-bottom: 24px;
}

.appointment-card {
  background: white;
  border-radius: 8px;
  padding: 16px;
  margin-bottom: 16px;
  box-shadow: 0 2px 8px rgba(0,0,0,0.1);
}

.apt-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12px;
}

.apt-info h4 {
  margin: 0 0 4px;
  color: #303133;
}

.apt-info p {
  margin: 0;
  color: #909399;
  font-size: 14px;
}

.apt-content {
  margin-bottom: 12px;
}

.apt-content p {
  margin: 8px 0;
  color: #606266;
  display: flex;
  align-items: center;
  gap: 8px;
}

.apt-actions {
  display: flex;
  gap: 8px;
}

.empty-state {
  text-align: center;
  padding: 40px 0;
}
</style>